package com.moduls.interfaceFunction.message;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

@Controller("MessageController")
@RequestMapping("/qt/Message")
public class MessageController{
	private static Log log = LogFactory.getLog(MessageController.class);
	private final String CHARSET = "UTF-8";
    private final String FORMAT = "json";
    public Map<String, String> setMessage(String phone, String type) throws IOException, ClientException {
		Map<String, String> result = new HashMap<String, String>();
		//设置超时时间-可自行调整
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
	    System.setProperty("sun.net.client.defaultReadTimeout", "10000");
	    //初始化ascClient需要的几个参数	
	    final String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
	    final String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
	    //替换成你的AK
	    final String accessKeyId = "LTAIv76e9yanR66I";//你的accessKeyId,参考本文档步骤2
	    final String accessKeySecret = "Cxt1VLaDMesQ11NJkvsPHmm4uFicT9";//你的accessKeySecret，参考本文档步骤2
	    //初始化ascClient,暂时不支持多region（请勿修改）
	    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
	    accessKeySecret);
	    DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
	    IAcsClient acsClient = new DefaultAcsClient(profile);
	     //组装请求对象
	     SendSmsRequest request = new SendSmsRequest();
	     //使用post提交
	     request.setMethod(MethodType.POST);
	     //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
	     request.setPhoneNumbers(phone);
	     //必填:短信签名-可在短信控制台中找到
	     request.setSignName("选我我选");
	     //必填:短信模板-可在短信控制台中找到
	     if(type.equals("1")){
	    	 request.setTemplateCode("SMS_139239627");
	     }
	     else if(type.equals("2")||type.equals("3")){
	    	 request.setTemplateCode("SMS_139239631");
	     }
	     else {
	    	 request.setTemplateCode("SMS_139234784");
	     }
	     String TemplateCode="SMS_139239627";
	     //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
	     //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败

	     Map<String, Object> templateMap = new HashMap<String, Object>();
//	     templateMap.put("操作", type);
     	String code=getFourRandom();//生成4位数验证码
     	templateMap.put("code",code);
	     String  template =JSONArray.fromObject(templateMap).toString();
	     template=template.substring(1,template.length()-1);
	     request.setTemplateParam(template);
//	     request.setTemplateParam("{\"code\":\"1234\"}");
	     //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
	     //request.setSmsUpExtendCode("90997");
	     //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
	     request.setOutId("yourOutId");
	    //请求失败这里会抛ClientException异常
	    SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
	    if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
	    //请求成功
	    	result.put("sms_code", code);
	    	result.put("type", type);
	    	result.put("sms_phone", phone);
	    	result.put("message", "发送成功");
	    }else if(sendSmsResponse.getCode().equals("isv.BUSINESS_LIMIT_CONTROL")){
	    	if(sendSmsResponse.getMessage().equals("触发分钟级流控Permits:1")) {
	    	result.put("message", "发送频繁，请在一分钟后重试");
	    	}else if(sendSmsResponse.getMessage().equals("触发小时级流控Permits:5")) {
	    	result.put("message", "发送频繁，请在一小时后重试");	
	    	}else {
	    	result.put("message", "发送频繁，请在一天后重试");	
	    	}
	    }else {
	    	result.put("message", "发送失败");
	    }
		return result;
	}
	 /**
     * 产生4位随机数(0000-9999)
     * @return 4位随机数
     */
    public static String getFourRandom(){
        Random random = new Random();
        String fourRandom = random.nextInt(10000) + "";
        int randLength = fourRandom.length();
        if(randLength<4){
          for(int i=1; i<=4-randLength; i++)
              fourRandom = "0" + fourRandom  ;
      }
        return fourRandom;
    } 
}
